//
//  HomepageViewController.m
//  HaoHaiSpell
//
//  Created by haohai on 16/6/13.
//  Copyright © 2016年 海城. All rights reserved.
//

#import "HomepageViewController.h"
#import "FourthSectionCell.h"
#import "SectionCell.h"
#import "HomepageCell.h"
#import "HeaderView.h"
#import "LimitTimeViewController.h"
#import "StriveViewController.h"
#import "NewViewController.h"
#import "ShoppingViewController.h"
#import "FreeViewController.h"
#import "HotViewController.h"
<<<<<<< HEAD
#import <AMapLocationKit/AMapLocationKit.h>
#import "MapLocationViewController.h"
#import "SpellModel.h"
#define LocationTimeout 10
#define ReGeocodeTimeout 5

#define k_url @"http://wfx.hostadmin.com.cn/app/app.php"
@interface HomepageViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UISearchBarDelegate,UICollectionViewDelegateFlowLayout,AMapLocationManagerDelegate>
=======

@interface HomepageViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UISearchBarDelegate,UICollectionViewDelegateFlowLayout>
>>>>>>> 5bee59541ff07dbcbaa6fe419e6df24b39c5e23d

@property (nonatomic,strong)UICollectionView *contentCollectionView;//集合视图
@property (nonatomic,strong)UIButton *locationBtn;//定位按钮
@property (nonatomic,strong)UISearchBar *contentSearchBar;//搜索框
<<<<<<< HEAD
=======
@property (nonatomic,strong)UIImageView *localIcon;//定位图标
>>>>>>> 5bee59541ff07dbcbaa6fe419e6df24b39c5e23d
@property (nonatomic,strong)NSMutableArray *allDataSource;//数据
@property (nonatomic,strong)NSMutableDictionary *parameter;//参数
@property (nonatomic,strong)UIView *smallView;
@property (nonatomic, strong) NSArray *titleArray;// 标题数组
@property (nonatomic,strong)UIScrollView *myScrollView;
@property (nonatomic,strong)UIButton *selBtn; //选中按钮
@property (nonatomic,strong)NSMutableArray *imageArr;//轮播图数组
@property (nonatomic,strong)NSArray *id_cellArray;
@property (nonatomic,assign)NSInteger index;//单元格下标
<<<<<<< HEAD
@property (nonatomic, strong) AMapLocationManager *locationManager;
@property (nonatomic,strong) NSString *locationName;//定位城市名称

=======
>>>>>>> 5bee59541ff07dbcbaa6fe419e6df24b39c5e23d

@end

@implementation HomepageViewController

#pragma mark - 懒加载
-(UICollectionView *)contentCollectionView{

    if (!_contentCollectionView) {
    UICollectionViewFlowLayout *layout=[[UICollectionViewFlowLayout alloc]init];
        layout.minimumLineSpacing=10;
        layout.minimumInteritemSpacing=10;
//        layout.sectionInset=UIEdgeInsetsMake(10, 10, 10, 10);
//      layout.itemSize=CGSizeMake(kWidth-20, (kHeight-30)/3);
<<<<<<< HEAD
        _contentCollectionView=[[UICollectionView alloc]initWithFrame:CGRectMake(0, 99, kWidth, kHeight - 99) collectionViewLayout:layout];
=======
        _contentCollectionView=[[UICollectionView alloc]initWithFrame:CGRectMake(0, 114, kWidth, kHeight - 144) collectionViewLayout:layout];
>>>>>>> 5bee59541ff07dbcbaa6fe419e6df24b39c5e23d
        _contentCollectionView.backgroundColor=HWColor(241, 241, 241);
        
        _contentCollectionView.delegate=self;
        _contentCollectionView.dataSource=self;
    }
    return _contentCollectionView;
}


-(UIButton *)locationBtn{

    if (!_locationBtn) {
        _locationBtn=[UIButton buttonWithType:UIButtonTypeSystem];
<<<<<<< HEAD
        [_locationBtn setTitle:self.locationName forState:UIControlStateNormal];
        [_locationBtn addTarget:self action:@selector(locationAction:) forControlEvents:UIControlEventTouchUpInside];
        _locationBtn.backgroundColor=[UIColor whiteColor];
        UIImage *btnImage = [UIImage imageNamed:@"location-ico.png"];
        btnImage = [btnImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        [_locationBtn setImage:btnImage forState:UIControlStateNormal];
        [_locationBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [_locationBtn.titleLabel setFont:[UIFont fontWithName:@"Helvetica-Bold" size:14]];
        [_locationBtn setFrame:CGRectMake(0, 64, 60, 35)];
=======
        [_locationBtn setTitle:@"中国" forState:UIControlStateNormal];
        [_locationBtn addTarget:self action:@selector(locationAction:) forControlEvents:UIControlEventTouchUpInside];
        _locationBtn.backgroundColor=[UIColor whiteColor];
        [_locationBtn setFrame:CGRectMake(40, 64, 50, 50)];
>>>>>>> 5bee59541ff07dbcbaa6fe419e6df24b39c5e23d
    }
    return _locationBtn;
}

<<<<<<< HEAD
-(UISearchBar *)contentSearchBar{

    if (!_contentSearchBar) {
        _contentSearchBar=[[UISearchBar alloc]initWithFrame:CGRectMake(60, 64, kWidth- 60, 35)];
=======

-(UIImageView *)localIcon{

    if (!_localIcon) {
        _localIcon=[[UIImageView alloc]initWithFrame:CGRectMake(0, 64, 40, 50)];
        _localIcon.backgroundColor=[UIColor whiteColor];
        _localIcon.image=[UIImage imageNamed:@"location-ico.png"];
    }
    return _localIcon;
}


-(UISearchBar *)contentSearchBar{

    if (!_contentSearchBar) {
        _contentSearchBar=[[UISearchBar alloc]initWithFrame:CGRectMake(90, 64, kWidth- 90, 50)];
>>>>>>> 5bee59541ff07dbcbaa6fe419e6df24b39c5e23d
        _contentSearchBar.placeholder=@"请输入要搜索的内容";
        [_contentSearchBar setImage:[UIImage imageNamed:@"top_s.png"] forSearchBarIcon:UISearchBarIconSearch state:UIControlStateNormal];
        _contentSearchBar.delegate=self;
        
    }
    return _contentSearchBar;
}

-(NSMutableDictionary *)parameter{

    if (!_parameter) {
<<<<<<< HEAD
        _parameter=[NSMutableDictionary dictionaryWithDictionary:@{@"op":@"index",@"act":@"team_list",@"page_size":@"1",@"verify":@"e10adc3949ba59abbe56e057f20f883e",@"site_id":@"西安市"}];
=======
        _parameter=[NSMutableDictionary dictionaryWithDictionary:@{@"key":@"value"}];
>>>>>>> 5bee59541ff07dbcbaa6fe419e6df24b39c5e23d
    }
    return _parameter;
}

<<<<<<< HEAD

=======
>>>>>>> 5bee59541ff07dbcbaa6fe419e6df24b39c5e23d
-(NSMutableArray *)allDataSource{

    if (_allDataSource) {
        _allDataSource=[[NSMutableArray alloc]init];
    }
    return _allDataSource;
}

- (NSArray *)titleArray
{
    if (!_titleArray) {
        _titleArray = @[@"限时秒杀", @"1元夺宝", @"店铺街", @"新人专享", @"0元专区", @"热榜"];
    }
    return _titleArray;
}

-(NSMutableArray *)imageArr{

    if (!_imageArr) {
        UIImage *image = [UIImage imageNamed:@"contentimg.jpg"];
        _imageArr=[NSMutableArray arrayWithArray:@[image,image,image]];
    }
    return _imageArr;
}



-(UIView *)smallView{
    
    if (!_smallView) {
        _smallView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, kWidth, kHeight / 2.5)];

        WFCarousel *shufflingView=[[WFCarousel alloc]initWithFrame:CGRectMake(0, 0, kWidth, kHeight/4) pictureArray:self.imageArr];
        [_smallView addSubview:shufflingView];
        _smallView.backgroundColor = [UIColor whiteColor];
        [self createBtn];
        
    }
    return _smallView;
}

-(NSArray *)id_cellArray{

    if (!_id_cellArray) {
        _id_cellArray=@[@"HomepageCell",@"sectionCell",@"fourthCell"];
    }
    return _id_cellArray;
}

#pragma mark - 自定义回调方法
// 定位按钮的回调方法
-(void)locationAction:(UIButton *)sender{

<<<<<<< HEAD
    MapLocationViewController *mapVC = [[MapLocationViewController alloc]init];
    [self addChildViewController:mapVC];
    CGRect frame = mapVC.view.frame;
    frame = CGRectMake(20, 94, kWidth - 40, kHeight);
    mapVC.view.frame = frame;
    [self.view addSubview:mapVC.view];
    NSLog(@"定位");
}

// 地图定位
-(void)Maplocation{

    self.locationManager = [[AMapLocationManager alloc] init];
    self.locationManager.delegate = self;
    [self.locationManager setDesiredAccuracy:kCLLocationAccuracyHundredMeters];
    
    [self.locationManager setPausesLocationUpdatesAutomatically:NO];
    
    [self.locationManager setAllowsBackgroundLocationUpdates:YES];
    
    [self.locationManager setLocationTimeout:LocationTimeout];
    
    [self.locationManager setReGeocodeTimeout:ReGeocodeTimeout];
}

-(void)startMapLocation{
    
    [self Maplocation];
    [self.locationManager requestLocationWithReGeocode:YES completionBlock:^(CLLocation *location, AMapLocationReGeocode *regeocode, NSError *error) {
        if (error) {
            NSLog(@"locError:{%ld - %@};", (long)error.code, error.localizedDescription);
        }
       NSLog(@"location:%@", location);
        if (regeocode)
        {
            NSLog(@"reGeocode:%@", regeocode);
            self.locationName = regeocode.city;
            NSLog(@"%@",self.locationName);
        }
    }];
}

-(void)stopMapLocation{
    
    [self.locationManager stopUpdatingLocation];
}



// 创建按钮
=======


    NSLog(@"定位");
}


>>>>>>> 5bee59541ff07dbcbaa6fe419e6df24b39c5e23d
-(void)createBtn{

    self.myScrollView=[[UIScrollView alloc]initWithFrame:CGRectMake(0, kHeight/4, kWidth, kWidth / 3)];
    self.myScrollView.showsHorizontalScrollIndicator = NO;
    
    for (int i = 0; i < self.titleArray.count; i++) {
        UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
        [self.myScrollView addSubview:button];
        button.titleLabel.font = [UIFont systemFontOfSize:17];
        button.titleLabel.textAlignment = NSTextAlignmentCenter;
        button.frame = CGRectMake((kWidth / 5 + 20) * i + 10, 5, kWidth / 5, kWidth / 5);
        [button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
        button.layer.cornerRadius = kWidth / 10;
        button.layer.masksToBounds = YES;
        button.tag = 1000 + i;
        [button setImage:[UIImage imageNamed:[NSString stringWithFormat:@"nav_1_%d.png",i+1]] forState:UIControlStateNormal];
        UILabel *titleLabel=[[UILabel alloc]initWithFrame:CGRectMake((kWidth / 5 + 20) * i + 10, kWidth / 5, kWidth / 5, 20)];
        titleLabel.textAlignment=NSTextAlignmentCenter;
        titleLabel.text=self.titleArray[i];
        [self.myScrollView addSubview:titleLabel];
    }
    self.myScrollView.contentSize = CGSizeMake((kWidth / 5 + 20) * self.titleArray.count, 0);
    [self.smallView addSubview:self.myScrollView];
}

// 按钮的回调方法
-(void)buttonClick:(UIButton *)sender{

    [self selTitleBtn:sender];
    NSInteger i = sender.tag - 1000;
    sender.highlighted = YES;
    self.myScrollView.contentOffset=CGPointMake(i * (kWidth / 5 + 20), 0);
    [self addChildViewController];
    NSLog(@"%ld",(long)sender.tag);
}

// 选中按钮
- (void)selTitleBtn:(UIButton *)btn
{
    [self.selBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    self.selBtn.transform = CGAffineTransformIdentity;
    
    [btn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    self.selBtn = btn;
}

#pragma mark - 添加子控制器
- (void)addChildViewController
{
    UIStoryboard *storyboard=[UIStoryboard storyboardWithName:@"BHJStoryboard" bundle:nil];
    switch (self.selBtn.tag) {
        case 1000:
        {
            LimitTimeViewController *limitVC=[[LimitTimeViewController alloc]init];
            limitVC.title = self.titleArray[0];
            [self.navigationController pushViewController:limitVC animated:YES];
        }
            break;
        case 1001:{
            StriveViewController *striveVC=[storyboard instantiateViewControllerWithIdentifier:@"StriveViewController"];
             striveVC.title = self.titleArray[1];
            [self.navigationController pushViewController:striveVC animated:YES];
        }
            break;
        case 1003:{
            NewViewController *newVC = [[NewViewController alloc]init];
            newVC.title = self.titleArray[3];
            [self.navigationController pushViewController:newVC animated:YES];
        }
            break;
        case 1002:{
<<<<<<< HEAD
            ShoppingViewController *shoppingVC=[[ShoppingViewController alloc]init];
=======
            ShoppingViewController *shoppingVC=[storyboard instantiateViewControllerWithIdentifier:@"ShoppingViewController"];
>>>>>>> 5bee59541ff07dbcbaa6fe419e6df24b39c5e23d
            shoppingVC.title = self.titleArray[2];
            [self.navigationController pushViewController:shoppingVC animated:YES];
        }
            break;
        case 1004:{
            FreeViewController *freeVC=[[FreeViewController alloc]init];
            freeVC.title = self.titleArray[4];
            [self.navigationController pushViewController:freeVC animated:YES];
        }
            break;
        case 1005:{
<<<<<<< HEAD
            HotViewController *hotVC=[[HotViewController alloc]init];
=======
            HotViewController *hotVC=[storyboard instantiateViewControllerWithIdentifier:@"HotViewController"];
>>>>>>> 5bee59541ff07dbcbaa6fe419e6df24b39c5e23d
            hotVC.title = self.titleArray[5];
            [self.navigationController pushViewController:hotVC animated:YES];
        }
            break;
        default:
            break;
    }
}



// 数据请求
-(void)fetchDataFromURL:(NSString *)url parameter:(NSDictionary *)parameter{

<<<<<<< HEAD
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager GET:url parameters:parameter progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        NSArray *contentArray = dic[@"content"];
        NSString *site_id = dic[@"site_id"];
        [Site_ID sharedSite_ID].site_id = site_id;
        for (NSDictionary *mDic in contentArray) {
            SpellModel  *model = [[SpellModel alloc]init];
            [model setValuesForKeysWithDictionary:mDic];
            
            NSLog(@"name------- %@",model.goods_name);
            [self.allDataSource addObject:model];
        }
        [self.contentCollectionView reloadData];
        NSLog(@"请求成功");
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求失败");
    }];

=======
 
>>>>>>> 5bee59541ff07dbcbaa6fe419e6df24b39c5e23d


}



#pragma mark - UISearchBarDelegate









#pragma mark - UICollectionViewDataSource

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{

    return 4;
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{

    if (section == 0) {
        return 0;
    }else if (section == 1){
        return 3;
    }else if (section == 2){
        return 2;
    }else if (section == 3){
        return 5;
    }else{
        return 0;
    }
}


-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 2) {
        
        SectionCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"sectionCell" forIndexPath:indexPath];
        cell.prePriceLabel.lineType=LineTypeMiddle;
        cell.prePriceLabel.lineColor=[UIColor lightGrayColor];
        return cell;
    }else{
        HomepageCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"HomepageCell" forIndexPath:indexPath];
        self.index = indexPath.row;
        if (indexPath.section == 3) {
             FourthSectionCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"fourthCell" forIndexPath:indexPath];
            cell.prePriceLabel.lineType=LineTypeMiddle;
            cell.prePriceLabel.lineColor=[UIColor lightGrayColor];
             return cell;
        }else{
        return cell;
        }
    }
}


-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{

<<<<<<< HEAD

=======
NSLog(@"%ld",(long)indexPath.row);
>>>>>>> 5bee59541ff07dbcbaa6fe419e6df24b39c5e23d
}


-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 0) {
        UICollectionReusableView *firstview=[collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"firstView" forIndexPath:indexPath];
        [firstview addSubview:self.smallView];
        return firstview;
    } else{
        
        HeaderView *view=[collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"headerView" forIndexPath:indexPath];
        if (indexPath.section == 1) {
            view.titleLabel.text=@"拼团专区";
        }else if (indexPath.section == 2) {
            
            view.titleLabel.text=@"0元专区";
        }else if (indexPath.section == 3){
            
            view.titleLabel.text=@"精品商城";
        }
        return view;
    }
}


-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    
    if (section == 0) {
        return CGSizeMake(kWidth, kHeight / 2.5);
    }else{
    return CGSizeMake(kWidth - 20, kHeight / 18);
    }
 }

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{

    if (indexPath.section == 3) {
<<<<<<< HEAD
        return CGSizeMake((kWidth- 30) / 2, (kHeight - 64)/ 3);
    }else if (indexPath.section == 2){
        return CGSizeMake(kWidth - 20, (kHeight - 64) / 4);
    }else{
         return CGSizeMake(kWidth - 20, (kHeight - 64) / 3);
    }
}




=======
        return CGSizeMake((kWidth- 30) / 2, kHeight / 3);
    }else if (indexPath.section == 2){
        return CGSizeMake(kWidth - 20, kHeight / 4);
    }else{
         return CGSizeMake(kWidth - 20, kHeight / 3);
    }
}

>>>>>>> 5bee59541ff07dbcbaa6fe419e6df24b39c5e23d
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{

    
    if (self.index == 0) {
        
      return UIEdgeInsetsMake(1, 10, 10, 10);
    }else{
    return UIEdgeInsetsMake(10, 10, 10, 10);
    }
}



#pragma mark - UIScrollViewDelegate





#pragma mark - 视图生命周期
- (void)viewDidLoad {
    [super viewDidLoad];
    
<<<<<<< HEAD
     self.locationName = @"中国";
    [self.view addSubview:self.locationBtn];
//    [self.view addSubview:self.localIcon];
=======
    [self.view addSubview:self.locationBtn];
    [self.view addSubview:self.localIcon];
>>>>>>> 5bee59541ff07dbcbaa6fe419e6df24b39c5e23d
    [self.view addSubview:self.contentSearchBar];
    [self.view addSubview:self.contentCollectionView];
    
    [self.contentCollectionView registerNib:[UINib nibWithNibName:@"HomepageCell" bundle:nil] forCellWithReuseIdentifier:@"HomepageCell"];
    [self.contentCollectionView registerNib:[UINib nibWithNibName:@"SectionCell" bundle:nil] forCellWithReuseIdentifier:@"sectionCell"];
    [self.contentCollectionView registerNib:[UINib nibWithNibName:@"FourthSectionCell" bundle:nil] forCellWithReuseIdentifier:@"fourthCell"];
    [self.contentCollectionView registerNib:[UINib nibWithNibName:@"HeaderView" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"headerView"];
    [self.contentCollectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"firstView"];
<<<<<<< HEAD
    
// 请求数据
    [self fetchDataFromURL:k_url parameter:self.parameter];
   // 地图定位
    [self startMapLocation];
    
    
=======
>>>>>>> 5bee59541ff07dbcbaa6fe419e6df24b39c5e23d
    // Do any additional setup after loading the view.
}



<<<<<<< HEAD



=======
>>>>>>> 5bee59541ff07dbcbaa6fe419e6df24b39c5e23d
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{

    [self.view endEditing:YES];
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

<<<<<<< HEAD
#pragma mark - AMapLocationManagerDelegate
-(void)amapLocationManager:(AMapLocationManager *)manager didUpdateLocation:(CLLocation *)location{

//    NSLog(@"location:{lat:%f; lon:%f; accuracy:%f}", location.coordinate.latitude, location.coordinate.longitude, location.horizontalAccuracy);
}


=======
>>>>>>> 5bee59541ff07dbcbaa6fe419e6df24b39c5e23d
@end
